package edu.johnpank.libassistant.config

import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import org.springframework.context.annotation.Bean
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer
import org.thymeleaf.spring5.SpringTemplateEngine
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver
import org.thymeleaf.spring5.view.ThymeleafViewResolver
import org.thymeleaf.templatemode.TemplateMode


class MvcConfig: WebMvcConfigurer, ApplicationContextAware {

    private lateinit var applicationContext: ApplicationContext

    override fun addViewControllers(registry: ViewControllerRegistry){
//        registry.addViewController("/login").setViewName("login_page")

    }


    private fun templateResolver(): SpringResourceTemplateResolver? {
        // SpringResourceTemplateResolver automatically integrates with Spring's own
        // resource resolution infrastructure, which is highly recommended.
        val templateResolver = SpringResourceTemplateResolver()
        templateResolver.setApplicationContext(this.applicationContext)
        templateResolver.prefix = "/WEB-INF/templates/"
        templateResolver.suffix = ".html"
        // HTML is the default value, added here for the sake of clarity.
        templateResolver.templateMode = TemplateMode.HTML
        // Template cache is true by default. Set to false if you want
        // templates to be automatically updated when modified.
        templateResolver.isCacheable = true
        return templateResolver
    }

    override fun setApplicationContext(applicationContext: ApplicationContext) {
        this.applicationContext = applicationContext
    }


    fun templateEngine(): SpringTemplateEngine? {
        // SpringTemplateEngine automatically applies SpringStandardDialect and
        // enables Spring's own MessageSource message resolution mechanisms.
        val templateEngine = SpringTemplateEngine()
        templateEngine.setTemplateResolver(templateResolver())
        // Enabling the SpringEL compiler with Spring 4.2.4 or newer can
        // speed up execution in most scenarios, but might be incompatible
        // with specific cases when expressions in one template are reused
        // across different data types, so this flag is "false" by default
        // for safer backwards compatibility.
        templateEngine.enableSpringELCompiler = true
        return templateEngine
    }

    @Bean
    fun viewResolver(): ThymeleafViewResolver? {
        val viewResolver = ThymeleafViewResolver()
        viewResolver.templateEngine = templateEngine()
        return viewResolver
    }
}
